import { ref, reactive, onMounted, onUnmounted } from 'vue'
export function getSearchValue(paramName) {
  const urlObj = new URL(window.location.href);
  return urlObj.searchParams.get(paramName);
}
export function useHIDManager() {
  // 响应式数据
  const devices = ref([])
  const connectBtnDisabled = ref(false)
  const status = reactive({
    show: false,
    message: '',
    type: 'success'
  })
  const deviceGroups = ref([])

  // 事件监听器引用
  let connectListener = null
  let disconnectListener = null

  // 初始化
  const init = () => {
    if (!navigator.hid) {
      showStatus('您的浏览器不支持WebHID API', 'error')
      connectBtnDisabled.value = true
      return
    }

    loadConnectedDevices()
    setupEventListeners()
  }

  // 设置事件监听器
  const setupEventListeners = () => {
    if (!navigator.hid) return

    // 监听设备连接
    connectListener = async (event) => {
      console.log('设备已连接:', event.device)
      showStatus(`设备已连接: ${event.device.productName || '未知设备'}`, 'success')
      await loadConnectedDevices()
    }

    // 监听设备断开
    disconnectListener = async (event) => {
      console.log('设备已断开:', event.device)
      showStatus(`设备已断开: ${event.device.productName || '未知设备'}`, 'warning')
      await loadConnectedDevices()
    }

    // 添加事件监听器
    navigator.hid.addEventListener('connect', connectListener)
    navigator.hid.addEventListener('disconnect', disconnectListener)
  }

  // 清理事件监听器
  const cleanupEventListeners = () => {
    if (navigator.hid && connectListener) {
      navigator.hid.removeEventListener('connect', connectListener)
    }
    if (navigator.hid && disconnectListener) {
      navigator.hid.removeEventListener('disconnect', disconnectListener)
    }
  }

  // 请求设备权限
  const requestDevice = async () => {
    try {
      connectBtnDisabled.value = true
      showStatus('正在请求设备访问权限...', 'success')
     
      let filters = window.HID_LIST?.map(device => ({
        vendorId: parseInt(device.vid, 16),
        productId: parseInt(device.pid, 16)
      }))
      if(getSearchValue('can_look_all_hid') == 1){
        filters = []
      }
      const requestedDevices = await navigator.hid.requestDevice({ filters })
      console.log('requestedDevices===:',requestedDevices)
      if (requestedDevices.length === 0) {
        showStatus('未选择任何设备', 'error')
      } else {
        showStatus(`成功连接 ${requestedDevices.length} 个设备`, 'success')
        await loadConnectedDevices()
      }
    } catch (error) {
      showStatus('连接设备失败: ' + error.message, 'error')
    } finally {
      connectBtnDisabled.value = false
    }
  }

  // 加载已连接的设备
  const loadConnectedDevices = async () => {
    try {
      const connectedDevices = await navigator.hid.getDevices()
      console.log('connectedDevices===:',connectedDevices)
      devices.value = connectedDevices
      processDeviceGroups()
    } catch (error) {
      showStatus('获取设备列表失败: ' + error.message, 'error')
    }
  }

  const to16 = (num) => {
    return `0x${num.toString(16).padStart(4, '0').toUpperCase()}`
  }
  // 处理设备分组
  const processDeviceGroups = () => {
    if (devices.value.length === 0) {
      deviceGroups.value = []
      return
    }

    // 不分组，直接处理每个设备
    deviceGroups.value = devices.value.map(device => {
      const productName = device.productName || '未知设备'
      const vendorId = device.vendorId ? `0x${device.vendorId.toString(16).padStart(4, '0').toUpperCase()}` : 'N/A'
      const productId = device.productId ? `0x${device.productId.toString(16).padStart(4, '0').toUpperCase()}` : 'N/A'
      
      console.log('device.collections===:',device.collections)

      return {
        devices: [device], // 每个设备作为一个单独的数组
        productName,
        vendorId,
        productId,
        vid: device.vendorId,
        pid: device.productId,
        usagePage: `0x${(device.collections?.[0]?.usagePage).toString(16).padStart(4, '0').toUpperCase()}`,
        usage:`0x${(device.collections?.[0]?.usage).toString(16).padStart(4, '0').toUpperCase()}`,
        usagePageArr:device.collections?.map(item=> to16(item.usagePage)),
        usageArr:device.collections?.map(item=> to16(item.usage)),
        displayName: productName
      }
    })
  }

  // 显示状态信息
  const showStatus = (message, type) => {
    status.show = true
    status.message = message
    status.type = type
    
    setTimeout(() => {
      status.show = false
    }, 3000)
  }

  // 获取设备显示名称列表（用于轮播图）
  const getDeviceDisplayList = () => {
    if (deviceGroups.value.length === 0) {
      return []
    }
    return deviceGroups.value
  }

  // 通过fetch获取list.json
  const fetchDeviceList = async () => {
    try {
      const JSONFiles = window.JSON_FILES || []
      
      // 并行请求所有JSON文件
      const fetchPromises = JSONFiles.map(fileName => 
        fetch(`./deviceJson/${fileName}`)
      )
      
      const responses = await Promise.all(fetchPromises)
      
      // 检查所有响应是否成功
      for (let i = 0; i < responses.length; i++) {
        if (!responses[i].ok) {
          throw new Error(`请求 ${JSONFiles[i]} 失败`)
        }
      }
      
      // 解析所有JSON数据
      const jsonPromises = responses.map(response => response.json())
      const allData = await Promise.all(jsonPromises)
      
      // 合并所有数组数据
      const mergedData = allData.flat()
      
      return mergedData
    } catch (error) {
      showStatus('获取设备列表失败: ' + error.message, 'error')
      return null
    }
  }

  // 组件挂载时初始化
  onMounted(() => {
    init()
  })

  // 组件卸载时清理
  onUnmounted(() => {
    cleanupEventListeners()
  })

  // 返回需要暴露的数据和方法
  return {
    // 数据
    devices,
    connectBtnDisabled,
    status,
    deviceGroups,
    
    // 方法
    requestDevice,
    loadConnectedDevices,
    showStatus,
    getDeviceDisplayList,
    fetchDeviceList,
    
    // 内部方法（可选择性暴露）
    init,
    processDeviceGroups,
    setupEventListeners,
    cleanupEventListeners
  }
} 